<?php

namespace app\api\service;

use app\api\model\AdminModel;
use app\api\model\ProductChannelModel;
use app\api\model\ProductCommissionModel;
use app\api\model\ProductModel;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class ProductChannelService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 配置开放产品
     */
    public function changeProductChannel($params)
    {
        $Validate = new Validate([
            'admin_id' => 'require',
            'channelData' => 'require',
        ], [
            'admin_id' => '设置账号标识无效',
            'channelData' => '佣金配置项必填'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $Validate = new Validate([
            'product_id' => 'require',
            'commission_type' => 'require',
            'status' => 'require'
        ], [
            'product_id' => '产品标识无效',
            'commission_type' => '佣金发放方式必填',
            'status' => '产品开放状态必填'
        ]);
        $checkData = $params['channelData'][0];
        if (!$Validate->check($checkData))
        {
            $this->error($Validate->getError());
        }
        Db::startTrans();
        try{
            $saveData = [];
            foreach ($params['channelData'] as $k => $v)
            {
                $proIds[] = $v['product_id'];
                $saveData[] = [
                    'product_id' => $v['product_id'],
                    'admin_id' => $params['admin_id'],
                    'commission_type' => $v['commission_type'],
                    'promotion_commission' => isset($v['promotion_commission']) ? $v['promotion_commission'] : 0,
                    'step_commission' => isset($v['step_commission']) ? json_encode($v['step_commission']) : '',
                    'c_time' => $this->stampToDateTime(time()),
                    'status' => $v['status']
                ];
            }
            ProductChannelModel::getInstance()->delete([
                'product_id' => ['IN', $proIds],
                'admin_id' => ['eq', $params['admin_id']]
            ]);
            $res = ProductChannelModel::getInstance()->insertAll($saveData);
            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 批量设置产品佣金
     */
    public function changeProductUserChannel($params)
    {
        $checkData = [
            'adminId' => 'require|array',
            'productData' => 'require|array',
        ];
        $checkMsg = [
            'adminId' => '用户标识无效',
            'productData' => '产品配置无效',
        ];
        $Validate = new Validate($checkData, $checkMsg);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        LogService::getInstance()->writeLogInfo($params);
        Db::startTrans();
        try{
            $proIds = array_column($params['productData'], 'productId');
            ProductChannelModel::getInstance()->delete([
                'product_id' => ['in', $proIds],
                'admin_id' => ['in', $params['adminId']]
            ]);
            foreach ($params['productData'] as $k => $v)
            {
                foreach ($params['adminId'] as $kk => $vv)
                {
                    $saveData[] = [
                        'product_id' => $v['productId'],
                        'admin_id' => $vv,
                        'commission_type' => $v['productCommissionType'],
                        'promotion_commission' => isset($v['productPromotionCommission']) ? $v['productPromotionCommission'] : 0,
                        'step_commission' => isset($v['productStepCommission']) ? json_encode($v['productStepCommission']) : json_encode([]),
                        'c_time' => $this->stampToDateTime(time()),
                        'u_time' => $this->stampToDateTime(time()),
                        'status' => 1,
                    ];
                }
            }
            $res = ProductChannelModel::getInstance()->insertAll($saveData);
            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取可配置佣金产品列表
     */
    public function getProductChannelList($params)
    {
        $Validate = new Validate([
            'admin_id' => 'require',
        ], [
            'admin_id' => '配置账号标识无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }

        //查询当前登录账号可见产品
        $adminIds = AdminModel::getInstance()->select([], 'id,username,nickname,pid', 0, 1000000);
        $adminIds = MenuService::getInstance()->getChildIds($adminIds, [$this->uid]);
        $adminProIds = ProductModel::getInstance()->selectProduct([
            'c_id' => ['in', $adminIds]
        ], 'id');
        $channelProIds = ProductChannelModel::getInstance()->select([
            'admin_id' => ['eq', $this->uid],
            'status' => ['eq', 1]
        ], 'product_id,commission_type,promotion_commission,step_commission,status');
        $proIds = array_merge(array_column($adminProIds, 'id'), array_column($channelProIds, 'product_id'));
        $proList = ProductModel::getInstance()->selectProduct([
            'id' => ['in', $proIds]
        ], 'id, product_name');

        //查询指定产品基础佣金  限制  配置佣金不可高于产品基础佣金
        $proCommission = ProductCommissionModel::getInstance()->column([
            'product_id' => ['in', $proIds]
        ], 'product_id, commission_type, promotion_commission, step_commission');

        //指定账号开放产品
        $adminProduct = ProductChannelModel::getInstance()->select([
            'admin_id' => ['eq', $params['admin_id']]
        ], 'product_id,commission_type,promotion_commission,step_commission,status');

        //组合当前登录账号和指定账号数据  输出信息
        $result = [];
        foreach ($proList as $k => $v)
        {
            $result[$k]['product_id'] = $v['id'];
            $result[$k]['product_name'] = $v['product_name'];
            $result[$k]['status'] = 0;
            $result[$k]['commission_type'] = 1;
            $result[$k]['promotion_commission'] = 0;
            $result[$k]['step_commission'] = [];
            $result[$k]['max_commission'] = 0;
            foreach ($proCommission as $kk => $vv)
            {
                if ($vv['product_id'] == $v['id'])
                {
                    $result[$k]['commission_type'] = $vv['commission_type'];
                    $result[$k]['promotion_commission'] = $vv['promotion_commission'];
                    $result[$k]['step_commission'] = json_decode($vv['step_commission'], true);
                    $result[$k]['max_commission'] = floatval($vv['promotion_commission']);
                    if ($vv['commission_type'] == 2)
                    {
                        $maxData = json_decode($vv['step_commission'], true);
                        $maxData = array_column($maxData, 'ratio');
                        $result[$k]['max_commission'] = floatval(max($maxData));
                    }
                    continue;
                }
            }
            foreach ($channelProIds as $kk => $vv)
            {
                if ($vv['product_id'] == $v['id'])
                {
                    $result[$k]['status'] = $vv['status'];
                    $result[$k]['commission_type'] = $vv['commission_type'];
                    $result[$k]['promotion_commission'] = $vv['promotion_commission'];
                    $result[$k]['step_commission'] = json_decode($vv['step_commission'], true);
                    continue;
                }
            }
            foreach ($adminProduct as $kk => $vv)
            {
                if ($vv['product_id'] == $v['id'])
                {
                    $result[$k]['status'] = $vv['status'];
                    $result[$k]['commission_type'] = $vv['commission_type'];
                    $result[$k]['promotion_commission'] = $vv['promotion_commission'];
                    $result[$k]['step_commission'] = json_decode($vv['step_commission'], true);
                    continue;
                }
            }
        }
        return $result;
    }
}